<?php
include '../config.php';

session_start();

$location = "Location: " . $ISSUER_HOST . "/remove_category_result.php";

// Connecting, selecting database
$mysqli = new mysqli($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD, $MYSQL_DB_NAME);
if ($mysqli->connect_errno) {
	$_SESSION[$CB_MSG_TAG] = $DB_CONN_ERR;
	$_SESSION[$DB_CONN_ERRNO] = $mysqli->connect_errno;
	$_SESSION[$DB_CONN_ERROR] = $mysqli->connect_error;
	header($location);
	exit();
}

$id=$_POST["nome"];

// Performing SQL query
//Update table badge
$query = sprintf($CATEGORY_BADGE, $id);
$result=$mysqli->query($query);
if (!$result) {
	mysqli_free_result($result);
	$mysqli->close();
	$_SESSION[$CB_MSG_TAG] = $QUERY_ERR;
	$_SESSION[$QUERY_TAG] = $query;
	$_SESSION[$QUERY_ERRNO] = $mysqli->errno;
	$_SESSION[$QUERY_ERROR] = $mysqli->error;
	header($location);
	exit();
}
else {
	$new_id=3;
	while($row=$result->fetch_assoc()){
		$badge=$row["badgeId"];
		$update_query=sprintf($UPDATE_CATEGORY, $new_id, $badge);
		$update=$mysqli->query($update_query);
		if (!$update) {
			mysqli_free_result($update);
			$mysqli->close();
			$_SESSION[$CB_MSG_TAG] = $QUERY_ERR;
			$_SESSION[$QUERY_TAG] = $update_query;
			$_SESSION[$QUERY_ERRNO] = $mysqli->errno;
			$_SESSION[$QUERY_ERROR] = $mysqli->error;
			header($location);
			exit();
		}
		
	} 
}
//Performing SQL remove query
$remove = sprintf($REMOVE_CATEGORY, $id);
$result_remove = $mysqli->query($remove);

if (!$result_remove) {
	$query = sprintf($CATEGORY_BADGE, $id);
	$result=$mysqli->query($query);
	while($row=$result->fetch_assoc()){
			$badge=$row["badgeId"];
			$restore_query=sprintf($UPDATE_CATEGORY, $id, $badge);
			$restore=$mysqli->query($restore_query);
	}
	mysqli_free_result($result_remove);
	$mysqli->close();
	$_SESSION[$CB_MSG_TAG] = $QUERY_ERR;
	$_SESSION[$QUERY_TAG] = $remove;
	$_SESSION[$QUERY_ERRNO] = $mysqli->errno;
	$_SESSION[$QUERY_ERROR] = $mysqli->error;
	header($location);
	exit();
}
 

// Closing connection
$mysqli->close();

$_SESSION[$CB_MSG_TAG] = $MSG_OK;
header($location);
exit();
?>
